package com.xp.flower.qsd.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.IURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.w3c.dom.Document;


public class WordToHtmlUtils {

	private WordToHtmlUtils() {}

	private static String docToHtml(MultipartFile uploadFile) {
		CommonsMultipartFile cf = (CommonsMultipartFile) uploadFile;
		DiskFileItem fi = (DiskFileItem) cf.getFileItem();
		File storeLocation = fi.getStoreLocation();
		String extension = FilenameUtils.getExtension(fi.getName());
		FileInputStream fileInputStream;
		String content = "";
		try {
			fileInputStream = new FileInputStream(storeLocation);
			if (extension.equalsIgnoreCase("doc")) {
				content = doc2003ToHtml(fileInputStream);
			} else if (extension.equalsIgnoreCase("docx")) {
				content = doc2007ToHtml(fileInputStream);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return content;
	}

	public static String docToHtmlWithOutHeadAndHtml(MultipartFile uploadFile) {
		return docToHtml(uploadFile)//
				.replace("<html>", "")//
				.replace("</html>", "")//
				.replace("<head>", "")//
				.replace("</head>", "");
	}

	private static String doc2003ToHtml(InputStream inputStream) {
		String content = "";
		try {
			HWPFDocument wordDocument = new HWPFDocument(inputStream);
			Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);

			wordToHtmlConverter.setPicturesManager(new PicturesManager() {
				@Override
				public String savePicture(byte[] content, PictureType pictureType, String name, float width,
						float height) {
					try (FileOutputStream out = new FileOutputStream(SystemPropertiesUtil
							.getProperty("local.image.dir") + name)) {
						out.write(content);
					} catch (Exception e) {
						e.printStackTrace();
					}
					String localFile = SystemPropertiesUtil.getProperty("local.image.dir") + name;
					String ftpFile = "";// FastDFSClient.uploadFile(new File(localFile), name);
					return SystemPropertiesUtil.getProperty("fdfs.ip.imageUrl") + ftpFile;
				}
			});
			wordToHtmlConverter.processDocument(wordDocument);
			Document htmlDocument = wordToHtmlConverter.getDocument();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			DOMSource domSource = new DOMSource(htmlDocument);
			StreamResult streamResult = new StreamResult(out);
			// StreamResult streamResult = new StreamResult(new
			// File("C:\\Users\\Administrator\\Desktop\\test.html"));

			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.ENCODING, "GBK");
			serializer.setOutputProperty(OutputKeys.INDENT, "yes");
			serializer.setOutputProperty(OutputKeys.METHOD, "html");
			serializer.transform(domSource, streamResult);

			out.close();
			content = new String(out.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}

	private static String doc2007ToHtml(InputStream inputStream) {
		String content = "";
		try {
			XWPFDocument document = new XWPFDocument(inputStream);
			XHTMLOptions options = XHTMLOptions.create();
			// 存放图片的文件夹
			options.setExtractor(new FileImageExtractor(new File(SystemPropertiesUtil.getProperty("local.image.dir"))));
			// html中图片的路径
			// options.URIResolver(new BasicURIResolver(imagePathStr));
			options.URIResolver(new IURIResolver() {
				@Override
				public String resolve(String uri) {
					int fileSuffixIndex = uri.lastIndexOf(".");
					String fileSuffix = uri.substring(fileSuffixIndex);
					String baseName = FilenameUtils.getBaseName(uri);

					String localFile = SystemPropertiesUtil.getProperty("local.image.dir") + uri;
					String ftpFile = "";//FastDFSClient.uploadFile(new File(localFile), baseName + fileSuffix);
					return SystemPropertiesUtil.getProperty("fdfs.ip.imageUrl") + ftpFile;
				}
			});
//			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream("C:/Users/Administrator/Desktop/test.html"), "GBK");
//			XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
//			xhtmlConverter.convert(document, outputStreamWriter, options);

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			XHTMLConverter.getInstance().convert(document, baos, options);
			content = baos.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}

}
